package com.qf.util;

import com.qf.entity.User;
import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtil {

    private static String key = "sdf8dsf76s8df76s56f6a8dfasdg9fg8df";

    //token的默认过期时间
    private static int ttl = 1000 * 60 * 60 * 24 * 7;

    /**
     * 根据用户信息生成用户token
     * @param user
     * @return
     */
    public static String getToken(User user, String devid){
        JwtBuilder builder = Jwts.builder()
                .setId(user.getId() + "")
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())//签发的时间
                //添加自定义属性
                .claim("id", user.getId())
                .claim("username", user.getUsername())
                .setExpiration(new Date(new Date().getTime() + ttl))//设置签名的过期时间
                .signWith(SignatureAlgorithm.HS256,key + devid);

        String jwtToken = builder.compact();
        return jwtToken;
    }

    /**
     * 根据令牌获得用户信息
     * @return
     */
    public static User getUserByToken(String token, String devid){
        //解析jwt token
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(key + devid)
                    .parseClaimsJws(token).getBody();

            //根据解析的对象生成User对象
            if (claims != null) {
                Integer id = (Integer) claims.get("id");
                String username = (String) claims.get("username");

                User user = new User()
                        .setId(id)
                        .setUsername(username);
                return user;
            }
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        User user = new User()
//                .setId(1)
//                .setUsername("admin");
//
//        String token = JwtUtil.getToken(user, "asdfasdfasd");
//        System.out.println(token);

//        User user = JwtUtil.getUserByToken("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoiYWRtaW4iLCJpYXQiOjE2MDY3MDU0ODEsImlkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwiZXhwIjoxNjA2NzA1NDgxfQ.Fu-uL7txu7MN_pTU9_YBQhFLtlG9xsYo3ayeKwCSJbE\n",
//                "asdfasdfasd");
//        System.out.println(user);
    }

}
